package com.kgcx.common.handler;

import com.kgcx.common.utils.IpUtils;
import com.kgcx.common.utils.ReflectHelper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * 拦截所有POST请求，如果发现有网络数据字段，则自动填入
 *
 * @author 吴刚林
 * @date 2018/5/10
 */
@ControllerAdvice
public class NetworkDataRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //拦截所有POST请求
        return request.getMethod().equalsIgnoreCase(HttpMethod.POST.toString());
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Field[] declaredFields = body.getClass().getDeclaredFields();
        if (ArrayUtils.isNotEmpty(declaredFields)) {
            for (Field declaredField : declaredFields) {
                if ("ip".equalsIgnoreCase(declaredField.getName())) {
                    ReflectHelper.setFieldValue(body, declaredField.getName(), IpUtils.getIpAddr(request));
                }
                if ("port".equalsIgnoreCase(declaredField.getName())) {
                    ReflectHelper.setFieldValue(body, declaredField.getName(), String.valueOf(request.getRemotePort()));
                }
            }
        }
        return body;
    }
}
